#include <func.h>

#define MAXLINE 1024

int tcp_connect(const char* host, const char* port)
{
    // 1.获取服务器端的地址
    struct addrinfo hints;
    bzero(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = 0;

    struct addrinfo *result, *p;
    int err = getaddrinfo(host, port, &hints, &result);
    if (err) {
        fprintf(stderr, "getaddrinfo():%s\n", gai_strerror(err));
        return -1;
    }

    int sockfd;
    for (p = result; p != NULL; p = p->ai_next) {
        // 创建主动套接字
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            continue;
        }
        // 连接
        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            continue;
        }
        break;
    } // p == NULL

    // 释放地址信息
    freeaddrinfo(result);

    if (p == NULL) {
        return -1;
    }
    return sockfd;
}

void do_echo(int connfd) 
{
    char sendline[MAXLINE];
    char recvline[MAXLINE];
    int n;
    while (fgets(sendline, MAXLINE, stdin) != NULL) {
        n = send(connfd, sendline, strlen(sendline) + 1, 0);
        if(n < 0) {
            error(1, errno, "send()");
        }
        // 发送成功
        n = recv(connfd, recvline, MAXLINE, 0);
        printf("%s", recvline);
    } // 读到 stdin 的末尾: ctrl + D
}

int main(int argc, char* argv[])
{
    // 连接服务器
    char host[] = "127.0.0.1";
    char port[] = "9527";

    int connfd = tcp_connect(host, port);
    if (connfd == -1) {
        error(1, errno, "tcp_connect()");
    }
    printf("INFO: connect %s:%s success\n", host, port);

    // 通信
    do_echo(connfd);

    shutdown(connfd, SHUT_RDWR);
    close(connfd);
    return 0;
}

